package com.hmsm.rtx;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hmsm.sys.bean.LocalDept;
import com.hmsm.sys.bean.LocalUser;

public class RTXDept<D extends LocalDept<D, U>, U extends LocalUser> {

	private static Log log = LogFactory.getLog(RTXDept.class);

	private Integer deptId;
	private int pdeptId;
	private String deptName;
	private int sortId;
	private RTXDept parent;
	private List<RTXDept> subDepts = new ArrayList<RTXDept>();
	private List<RTXUser> users = new ArrayList<RTXUser>();
	private D bindDept; // 绑定的本地部门

	public D getBindDept() {
		return bindDept;
	}

	public List<RTXUser> getUsers() {
		return users;
	}

	public void setUsers(List<RTXUser> users) {
		this.users = users;
	}

	public RTXDept getParent() {
		return parent;
	}

	public void setParent(RTXDept parent) {
		this.parent = parent;
	}

	public List<RTXDept> getSubDepts() {
		return subDepts;
	}

	public void setSubDepts(List<RTXDept> subDepts) {
		this.subDepts = subDepts;
	}

	public Integer getDeptId() {
		return deptId;
	}

	public void setDeptId(Integer deptId) {
		this.deptId = deptId;
	}

	public int getPdeptId() {
		return pdeptId;
	}

	public void setPdeptId(int pdeptId) {
		this.pdeptId = pdeptId;
	}

	public String getDeptName() {
		return deptName;
	}

	public void setDeptName(String deptName) {
		this.deptName = deptName;
	}

	public int getSortId() {
		return sortId;
	}

	public void setSortId(int sortId) {
		this.sortId = sortId;
	}

	public List<RTXDept> getAllDepts() {
		List<RTXDept> allDepts = new ArrayList<RTXDept>();

		for (RTXDept subDept : subDepts) {
			allDepts.add(subDept);
			List<RTXDept> list = subDept.getAllDepts();
			for (RTXDept sub1Dept : list) {
				allDepts.add(sub1Dept);
			}
		}

		return allDepts;
	}

	public List<RTXUser> getAllUsers() {
		List<RTXUser> allUsers = new ArrayList<RTXUser>();

		for (RTXUser user : users) {
			allUsers.add(user);
		}

		for (RTXDept depart : getAllDepts()) {
			for (Object user : depart.getUsers()) {
				allUsers.add((RTXUser) user);
			}
		}
		return allUsers;
	}

	public int getLevel() {
		int level;

		if (parent == null) {
			level = 2;
		} else {
			level = parent.getLevel() + 1;
		}

		return level;
	}

	public boolean isOrganization() {
		if (getLevel() == 3) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 获取所属组织机构
	 * @return
	 */
	public RTXDept getOrg() {
		RTXDept rtxOrg = null;

		if (!isOrganization() && parent != null) {
			if (parent.isOrganization()) {
				rtxOrg = parent;
			} else {
				rtxOrg = parent.getOrg();
			}
		}

		return rtxOrg;
	}

}
